<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="姓名">
              <a-input v-model="queryParam.keyword" placeholder=""/>
            </a-form-item>
          </a-col> 
          <template v-if="advanced">
            <a-col :md="8" :sm="24">
              <a-form-item label="调用次数">
                <a-input-number v-model="queryParam.callNo" style="width: 100%"/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="更新日期">
                <a-date-picker v-model="queryParam.date" style="width: 100%" placeholder="请输入更新日期"/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="使用状态">
                <a-select v-model="queryParam.useStatus" placeholder="请选择" default-value="0">
                  <a-select-option value="0">全部</a-select-option>
                  <a-select-option value="1">关闭</a-select-option>
                  <a-select-option value="2">运行中</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="使用状态">
                <a-select placeholder="请选择" default-value="0">
                  <a-select-option value="0">全部</a-select-option>
                  <a-select-option value="1">关闭</a-select-option>
                  <a-select-option value="2">运行中</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </template>
          <a-col :md="!advanced && 8 || 24" :sm="24">
            <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
              <a-button type="primary" @click="onSearch">查询</a-button>
              <a-button style="margin-left: 8px" @click="() => queryParam = {}">重置</a-button>
              <a @click="toggleAdvanced" style="margin-left: 8px" v-if="false">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <div class="table-operator">
      <a-button type="primary" icon="plus" @click="handleAdd" >新建</a-button>
      <a-dropdown v-if="  selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1"><a-icon type="delete" />删除</a-menu-item> 
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作 <a-icon type="down" />
        </a-button>
      </a-dropdown>
    </div>
    <s-table
            ref="table"
            size="default"
            :columns="columns"
            :data="loadData"
            :alert="{ show: true, clear: () => { this.selectedRowKeys = [] } }"
            :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
    >
      <span slot="tags" slot-scope="tags">
        <a-tag v-for="tag in tags" :key="tag.id" color="blue">{{tag.name}}</a-tag>
      </span>
      <span slot="action" slot-scope="text, record">
        <template >
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
        </template>
        <a-dropdown>
          <a class="ant-dropdown-link">
            更多 <a-icon type="down" />
          </a>
          <a-menu slot="overlay">
            <a-menu-item >
              <a-popconfirm title="确定删除吗?" @confirm="delConfirm(record)"  okText="确定" cancelText="取消">
    <a href="javascript:;">删除</a>
  </a-popconfirm>
            </a-menu-item>
          </a-menu>
        </a-dropdown>
      </span>
    </s-table>

    <a-modal
            title="操作"
            :width="800"
            v-model="visible"
            @ok="handleOk"
    >
      <a-form :form = form>
           <a-form-item
           v-show="false"  
        >
          <a-input  style="width: 100%" v-decorator="[
          'id',
          {rules: [ ]}
        ]" />
        </a-form-item>
     

        <a-form-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="姓名"
                hasFeedback
        >
          <a-input v-decorator="[
          'name',
          {rules: [{ required: true, message: '请输入姓名' }]}
        ]"
         placeholder="请输入姓名" />
        </a-form-item>

        <a-form-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="性别"
        >
          <a-select  v-decorator="[
              'sex',
              {rules: [{ required: true, message: '请选择性别' }]}
              ]"
               placeholder="请选择性别">
            <a-select-option value="男">男</a-select-option>
            <a-select-option value="女">女</a-select-option>
          </a-select>
        </a-form-item>
   <a-form-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="身份证"
                hasFeedback
        >
          <a-input v-decorator="[
          'cardCode',
          {rules: [{ required: true, message: '请输入身份证号' }]}
        ]"
         placeholder="请输入身份证号" />
        </a-form-item>
           <a-form-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="手机号"
                hasFeedback
        >
          <a-input v-decorator="[
          'phone',
          {rules: [{ required: true, message: '请输入手机号' }]}
        ]"
         placeholder="请输入手机号" />
        </a-form-item>
           <a-form-item
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
                label="地址"
                hasFeedback
        >
          <a-input v-decorator="[
          'address',
          {rules: [{ required: true, message: '请输入地址' }]}
        ]"
         placeholder="请输入地址" />
        </a-form-item>


         <a-form-item    
         :label="'孩子'+(index+1)"
                :labelCol="labelCol"
                :wrapperCol="wrapperCol"
      v-for="(children,index) in formData.childrenList"
      :key="index"
     >    
           <a-select   
              v-model ='children.studentId'
              allowClear
              showSearch
              :filterOption ="false"
              @search="childrenSelectSearch" 
               placeholder="请输入孩子名称" 
               style="width: 160px; margin-right: 20px"
               > 
            <a-select-option 
             v-for="(childrenOption,cindex) in childrenSearchOtions" :key="cindex"
              :value="childrenOption.id" >{{childrenOption.name}}</a-select-option> 
          </a-select> 
         <a-auto-complete
         v-model ='children.relationName'
          
    placeholder="关系类型"
      style="width: 160px; margin-right: 20px"
  >
    <template slot="dataSource">
      <a-select-option  v-for="(relationName,rindex) in realationNameOptions"  :key="rindex" :value="relationName" >{{relationName}}</a-select-option>
    </template>
  </a-auto-complete>  
      <a-icon
        v-if="formData.childrenList.length > 0"
        class="dynamic-delete-button"
        type="minus-circle-o"
        @click="() => childrenRemove(children)"
      /> 
    </a-form-item>
    <a-form-item   
      >
      <a-row> 
         <a-col :offset="6">
      <a-button
        type="dashed"
        style="width: 300px"
        @click="childrenAdd"
      >
        <a-icon type="plus" />增加孩子
      </a-button>
       </a-col>
      </a-row>
    </a-form-item>

      </a-form>
    </a-modal>
  
  </a-card>
</template>

<script>
  import STable from '@/components/table/'
  import ATextarea from 'ant-design-vue/es/input/TextArea'
  import AInput from 'ant-design-vue/es/input/Input'
  import moment from 'moment'

  import { getRoleList, getFamliyList, addFamliy, getFamliy, editFamliy, delFamliy,getChildrenSelect} from '@/api/manage'

  export default {
    name: 'FamliyList',
    components: {
      AInput,
      ATextarea,
      STable
    },
    data () {
      return {
        visible: false,
//        description: '全校班级管理。',
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 12 },
        },
       form: this.$form.createForm(this),
        mdl: {},

        // 高级搜索 展开/关闭
        advanced: false,
        // 查询参数
        queryParam: {},
        // 表头
        columns: [
          {
            title: '手机',
            dataIndex: 'phone',
          },
          {
            title: '姓名',
            dataIndex: 'name'
          },
          {
            title: '住址',
            dataIndex: 'address'
          },
          {
            title: '性别',
            dataIndex: 'sex'
            }
            , 
          {
            table: '操作',
            dataIndex: 'action',
            width: '150px',
            scopedSlots: { customRender: 'action' },
          }
        ],
        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {  
          return getFamliyList(Object.assign(parameter, this.queryParam))
                  .then(res => {
                    return res.result
                  })
        },

        selectedRowKeys: [],
        selectedRows: [], 
        parentShow: false, 
       formData:{
         childrenList: []
       },
       realationNameOptions:['父亲','母亲','爷爷','奶奶','外婆','外公'],
       childrenSearchOtions:[]
      }
    },
    created () {
      getRoleList({ t: new Date()})
    },
    methods: {
       // 家长设置
    parentSet(record){
      // this.parentShow = true; 
    },
    childrenRemove(children) {
      this.formData.childrenList= this.formData.childrenList.filter(key => key !== children)
    },  
    childrenAdd() { 
      this.formData.childrenList.push({ 
      }) 
    },

    childrenSelectSearch(value){
      console.log(value);
      let self = this;
      getChildrenSelect(value).then( res => {
        console.log(res);
        self.childrenSearchOtions = res.result;
      })
    },


        // 增
    handleAdd() {
      this.visible = true
      this.form.resetFields()
      this.formData.childrenList = []
    },
    // 改
    handleEdit(record) {
      this.form.resetFields()
      let self = this
      getFamliy({ familyId: record.id }).then(res => {
        self.form.setFieldsValue({ ...res.result });
        self.childrenSearchOtions =  { ...res.result.childrenList } ;
        self.formData.childrenList = [];
        res.result.childrenList.map((item) => {
          item.id = item.studentId;
          self.formData.childrenList.push(item);
        }) 
      })
      // console.log(this.mdl)
      this.visible = true
    },
    // 增改 处理
    handleOk(e) {
      let self =this;
      e.preventDefault()
      let parentValidate = true;
       this.formData.childrenList.map((item)=>{
         if((typeof item.studentId != 'undefined' ) && item.studentId != ''){
           if(item.relationName){
            return;
           } else {
             self.$message.error('请选择亲属关系'); 
             parentValidate = false
           }
         } else {
             self.$message.error('请选择学生');  
            parentValidate = false
         }   
      })
    //  ,{children:this.childrenList}
     if(!parentValidate){
       return ;
     } else {
        //this.form.getFieldDecorator('children', { initialValue: this.childrenList, preserve: true });
        this.form.validateFields((err, values) => {
        if (!err) {
          console.log('Received values of form: ', values)
            values.children= JSON.stringify(this.formData.childrenList);
          if (values.id) {
            let self = this
            editFamliy(values).then(res => {
              if(res.success){
                self.$message.success('修改成功')
                self.$refs.table.refresh(true)
                self.visible = false
              }else{
                self.$message.error(res.message)
              }  
              
            })
          } else {
            let self = this 
            addFamliy(values).then(res => {
              if(res.success){
                self.$message.success('添加成功')
                self.$refs.table.refresh(true)
                self.visible = false
              }else{
                self.$message.error(res.message)
              } 
            }).catch( err=>{
              console.log(err)
            })
          }
        }
      })
     }
         

  
        
    
      
    },
    // 删
    delConfirm(record) {
      console.log(record)
      let self = this
      delFamliy({ ids: record.id }).then(res => {
       if(res.success){
        self.$message.success('删除成功')
        self.$refs.table.refresh(true)
        }else{
          self.$message.error(res.message)
        }  
      })
    },
    // 查
    onSearch() {
      console.log(this.$refs.table.localPagination)
      console.log(this.queryParam)
      let self = this
      getFamliyList(this.queryParam).then(res => {
        self.$refs.table.refresh(true)
      })
    },

      onSelectChange (selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectedRows
      },
      toggleAdvanced () {
        this.advanced = !this.advanced
      },

      resetSearchForm () {
        this.queryParam = {
          date: moment(new Date())
        }
      }
    },
    watch: {
      /*
       'selectedRows': function (selectedRows) {
       this.needTotalList = this.needTotalList.map(item => {
       return {
       ...item,
       total: selectedRows.reduce( (sum, val) => {
       return sum + val[item.dataIndex]
       }, 0)
       }
       })
       }
       */
    }
  }
</script>